import { useCallback } from 'react';
import { DynamicCrudPage } from '@/components';
import type { TableConfig } from '@/components/DynamicTable/types';
import { getTableConfigByCode } from '@/api/tableConfig';
import { transformTableConfig } from '@/utils/tableConfigTransform';
import { transformEditData, transformSubmitData } from '@/utils/formDataTransform';
import { getPermissions, createPermission, updatePermission, deletePermission } from '@/api/permission';

const PermissionManagement = () => {
  const fetchConfigApi = useCallback(async (): Promise<TableConfig> => {
    const configRecord = await getTableConfigByCode('permissions');
    if (!configRecord) {throw new Error('权限表格配置不存在');}
    return transformTableConfig(configRecord);
  }, []);

  const wrappedUpdateApi = async (data: any) => {
    const { id, ...updateData } = data;
    return updatePermission(id, updateData);
  };

  return (
    <DynamicCrudPage
      fetchConfigApi={fetchConfigApi}
      fetchApi={getPermissions}
      createApi={createPermission}
      updateApi={wrappedUpdateApi}
      deleteApi={deletePermission}
      transformEditData={transformEditData}
      transformFormData={(data, mode) => transformSubmitData(data)}
      title="权限管理"
    />
  );
};

export default PermissionManagement;
